package org.brisling.sysman.queryService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpSession;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.domain.RetDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.SessionExpiredException;
import org.brisling.common.util.LongUtil;
import org.brisling.sysman.domain.Permissions;
import org.brisling.sysman.domain.Users;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/permission/query")
public class QueryPermissionService extends AbstractBaseQueryService<Permissions>{
	
	@Autowired
	private QueryDictionaryService dicService;
	
	@Autowired
	private QueryUserService qryUserService;
	
	private static Logger log = Logger.getLogger(QueryPermissionService.class);
	
	private String superUserIdentify;
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	public QueryPermissionService(){
		this.moduleName = ConstSysParam.MODULE_PERMISSION;
		this.subSystem = ConstSysParam.SUBSYSTEM_SYSMAN;
		this.tableName = this.getTableName(Permissions.class);
		this.clazz = Permissions.class;
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}	
	
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<Permissions> getListDomain(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="sort",required=false) String sort){		
		
		String sql = String.format(this.T_SQL, this.tableName);
		return super.getPagedListDomain(page, rows,sql);
	}
	
	@RequestMapping("/getFlowList.action")
	public List<Permissions> getFlowList(){		
		
		String sql = String.format(this.TW_SQL, this.tableName,"flowid is not null and (isused ='Y' or defaultused is not null) ");
		
		return super.getAllList(sql);
		
	}
	
	@RequestMapping("/getTreeListDomain.action")
	public ListDomain<Permissions> getTreeListDomain(@RequestParam(value="id",required=false) Long id){
		
		return this.getPagedTreeListDomain(id);
		
	}
	
	@RequestMapping("/getTreeList.action")
	public List<Permissions> getTreeList(@RequestParam(value="id",required=false) Long id){
		
		return this.getPagedTreeList(id);
		
	}
		
	@RequestMapping("/getOne.action")
	public Permissions getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 
	 * @return 用户具备访问权限的业务模块清单
	 * @throws Exception 
	 */
	
	@RequestMapping("/getUserMenu.action")
	@ResponseBody
	public List<Permissions> getUserMenu(@RequestParam(value="identity",required=false) String identify,HttpSession session){	
		
		String sql = "";		
		
		String _site = "risk";
		
		//获取session site
		Object siteObj = session.getAttribute(ConstSysParam.SITE_SESSION);
		if(siteObj!=null){
			String sessionSite = siteObj.toString().trim();
			if(sessionSite.length()>0){
				_site = sessionSite;
			}
		}
		
		//获取用户唯一编码
		if(identify==null){
			Users user = shiroSecurityService.getCurrentUser();
			if(user.getId()==null)
				return null;
			else
				identify=user.getId().toString();			
		}
		
		Long uid = LongUtil.getLongValue(identify, null);
		List<Permissions> permissionsList =  SysConfig.getUserMenuPermissionMap(uid, _site);
		
		if(permissionsList!=null && permissionsList.size()>0){
			return permissionsList;
		}else{
			superUserIdentify=SysConfig.getConfig(ConstSysParam.SUPER_USER_IDENTIFY);
			if (superUserIdentify.compareTo(identify)==0)
			{
				
				sql =String.format(dicService.getSqlByBizcode("admin_user_menu"),_site);
				
			}else{
				String normal_sql =dicService.getSqlByBizcode("normal_user_menu");
				String userCondition = String.format(" and u.id = '%1$s'", identify);
				sql= String.format(normal_sql,userCondition,_site);						
			}
			
			permissionsList = super.getAllList(sql);
			
			//循环迭代生成linkedhashmap		
			List<Permissions> parentList=new ArrayList<Permissions>();
			for (Permissions obj : permissionsList)
			{	
	//			System.out.println("name:"+obj.getName() +",parentid:"+obj.getParentid());
				if (obj.getParentid()==null)
				{
					
					List<Permissions> childList=new ArrayList<Permissions>();
					for (Permissions obj2 : permissionsList){
						
						if ( (obj2.getParentid()!=null) && (obj2.getParentid().equals(obj.getId()))){						
							childList.add(obj2);
						}
					}
					obj.setChild(childList);
					parentList.add(obj);
				}
			}
			SysConfig.setUserMenuPermissionMap(uid, _site, parentList);
			return parentList;
		}
	}
	
	/**
	 * 获取工作职能
	 * @param identify
	 * @param session
	 * @return
	 */
	@RequestMapping("/getUserDutiesMenu.action")
	@ResponseBody
	public List<Permissions> getUserDutiesMenu(@RequestParam(value="identity",required=false) String identify,HttpSession session){	
		
		List<Permissions> lists = this.getUserMenu(identify, session);
		
		List<Permissions> retLists = null;
		if(lists!=null){
			for(Permissions p:lists){				
				
				if(p!=null){
					if(p.getBizcode()!=null && p.getBizcode().trim().toLowerCase().compareTo("workduties")==0){
						retLists = p.getChild();
					}
				}
			}
		}
		
		return retLists;
	}
	/**
	 * 
	 * @return 用户具备访问权限的业务模块清单
	 * @throws SessionExpiredException 
	 * @throws Exception 
	 */	
	@RequestMapping("/getUserBizOperate.action")
	@ResponseBody
	public List<Permissions> getUserBizOperate(@RequestParam(value="identify",required=false)String identify,
			@RequestParam(value="bizcode",required=false)String bizcode,@RequestBody String body)  {	
		
//		if(userid==null)
//			throw new SessionExpiredException();
		
		if(identify==null){
			Users user = shiroSecurityService.getCurrentUser();
			if(user.getId()==null)
				return null;
			else
				identify=user.getId().toString();			
		}
		
//		if(userid!=user.getId())
//			throw new SessionExpiredException();
		
		if((bizcode==null)||(bizcode.trim().length()<=0)){
//			throw new BizCodeMustNotNullException();
			return null;
		}
		
		List<Permissions> permissionsList =  SysConfig.getUserPermissions(LongUtil.getLongValue(identify, null), bizcode);
		
		
		if(permissionsList!=null && permissionsList.size()>0){
			return permissionsList;
		}else{
			String _bizcode = "%" +bizcode+":%";
			String normal_sql =dicService.getSqlByBizcode("normal_user_operate");
			String sql = "";	
			String orderCorse = " order by sortedid";
			superUserIdentify=SysConfig.getConfig(ConstSysParam.SUPER_USER_IDENTIFY);
			if (superUserIdentify.compareTo(identify)==0)
			{
				
				sql = String.format(normal_sql, _bizcode,"",orderCorse);
			}else{
				String identity_sql =String.format(" AND u.id = '%1$s' ",identify);
				sql = String.format(normal_sql, _bizcode,identity_sql,orderCorse);						
			}
			
			log.debug(sql);
			
			permissionsList = super.getAllList(sql);
			if(permissionsList!=null && permissionsList.size()>0)
				SysConfig.setUserPermissions(LongUtil.getLongValue(identify, null), bizcode, permissionsList);
			
			return permissionsList;
		}
	}
	
	/**
	 * 
	 * @return 用户具备访问权限的业务模块清单
	 * @throws SessionExpiredException 
	 * @throws Exception 
	 */	
	@RequestMapping("/getBsUserBizBtn.action")
	@ResponseBody
	public List<Permissions> getBsUserBizBtn(
			@RequestParam(value="identify",required=false)String identify,
			@RequestParam(value="bizcode",required=false)String bizcode,
			@RequestParam(value="bizType",required=false)String bizType,
			@RequestBody String body)  {	
		
//		if(userid==null)
//			throw new SessionExpiredException();
		
		if(identify==null){
			Users user = shiroSecurityService.getCurrentUser();
			if(user.getId()==null)
				return null;
			else
				identify=user.getId().toString();			
		}
		
//		if(userid!=user.getId())
//			throw new SessionExpiredException();
		
		if((bizcode==null)||(bizcode.trim().length()<=0)){
//			throw new BizCodeMustNotNullException();
			return null;
		}
		
		List<Permissions> permissionsList =  SysConfig.getUserPermissions(LongUtil.getLongValue(identify, null), bizcode);
		
		
		if(permissionsList!=null && permissionsList.size()>0){
			return permissionsList;
		}else{
			String _bizcode = "%" +bizcode+":%";
			String normal_sql =dicService.getSqlByBizcode("normal_user_operate");
			String sql = "";	
			String orderCorse = " order by sortedid";
			superUserIdentify=SysConfig.getConfig(ConstSysParam.SUPER_USER_IDENTIFY);
			if (superUserIdentify.compareTo(identify)==0)
			{
				
				sql = String.format(normal_sql, _bizcode,"",orderCorse);
			}else{
				String identity_sql =String.format(" AND u.id = '%1$s' ",identify);
				sql = String.format(normal_sql, _bizcode,identity_sql,orderCorse);						
			}
			
			log.debug(sql);
			
			permissionsList = super.getAllList(sql);
			if(permissionsList!=null && permissionsList.size()>0)
				SysConfig.setUserPermissions(LongUtil.getLongValue(identify, null), bizcode, permissionsList);
			
			return permissionsList;
		}
	}
	
	/**
	 * 获取流程配置信息
	 * @param field
	 * @param fieldVal
	 * @return
	 */
	@RequestMapping("/getBizFlowConfig.action")
	public Permissions getBizFlowConfig(@RequestParam(value="bizcode",required=false) String bizcode){
		
		if(bizcode!=null){
			return super.getOneByIdentify("bizcode",bizcode);
		}
		return null;
		
	}
	
	@RequestMapping("/getOneByField.action")
	public Permissions getOneByField(@RequestParam(value="field",required=false) String field,@RequestParam(value="fieldVal",required=false) String fieldVal){	
		return super.getOneByIdentify(field,fieldVal);
	}
	
	
	@RequestMapping("/reloadCache.action")
	public RetDomain reloadCache(){	
		RetDomain domain = new RetDomain();		
		
		//刷新用户权限
		SysConfig.setPermissionRefreshCalendar();
		
		//重新加载完整模块代码(fullbizcode)所定义的流程业务定义
		SysConfig.setFlowBizMap(this.initFullbizcodeMaps());
		
		//重新加载模块代码(bizcode)所定义的流程业务定义
		SysConfig.setFlowBizcodeMap(this.initBizcodeMaps());
		
		//刷新管理用户
		qryUserService.reloadCache();
		
		//刷新用户缓存
		SysConfig.clearUserCache();
		
		domain.setSuccessMsg("success");
		
		
		return domain;
		
		
	}
	
	@PostConstruct
	public void initialize(){
		Map<String,Permissions> maps= SysConfig.getFlowBizMap();
		if(maps==null || maps.isEmpty())
			SysConfig.setFlowBizMap(this.initFullbizcodeMaps());
		
		Map<String,Permissions> bizcodeMaps= SysConfig.getFlowBizcodeMap();
		if(bizcodeMaps==null || bizcodeMaps.isEmpty())
			SysConfig.setFlowBizcodeMap(this.initBizcodeMaps());
	}
	/**
	 * 查询流程业务集合并封装为map
	 * @return
	 */
	private HashMap<String,Permissions> initFullbizcodeMaps(){
		HashMap<String,Permissions> maps = null;
		List<Permissions> lists = this.getFlowList();
		if(lists!=null &&(!lists.isEmpty())){
			maps = new HashMap<String,Permissions>();
			for(Permissions p:lists){
				maps.put(p.getFullBizcode(), p);
			}
		}
		
		return maps;
	}
	
	/**
	 * 查询流程业务集合并封装为map
	 * @return
	 */
	private HashMap<String,Permissions> initBizcodeMaps(){
		HashMap<String,Permissions> maps = null;
		List<Permissions> lists = this.getFlowList();
		if(lists!=null &&(!lists.isEmpty())){
			maps = new HashMap<String,Permissions>();
			for(Permissions p:lists){
				maps.put(p.getBizcode(), p);
			}
		}
		
		return maps;
	}

	/**
	 * 根据sql返回结果list
	 */
	public List<Permissions> getAllBySql(String sql){
		return super.getAllList(sql);
	}
}
